class Solution(object):
    def largestIsland(self, grid):
        n = len(grid)
        p = [0] * n ** 2
        rank = [0] * n ** 2
        def find(x):
            if p[x] == x:
                return p[x]
            else:
                p[x] = find(p[x])
                return p[x]

        def union(x, y):
            rx = find(x)
            ry = find(y)
            if rx != ry:
                if rx > ry:
                    p[rx] = ry
                    rank[ry] += rank[rx]
                else:
                    p[ry] = rx
                    rank[rx] += rank[ry]

        for i in range(n):
            for j in range(n):
                if grid[i][j]:
                    p[n * i + j] = n * i + j
                    rank[n * i + j ] = 1
                    if i > 0 and grid[i - 1][j]:
                        union(n * i + j, n * (i - 1) + j)
                    if j > 0 and grid[i][j - 1]:
                        union(n * i + j, n * i + j - 1)
        max_val = 0
        for i in range(n):
            for j in range(n):
                if grid[i][j]:
                    max_val = max(max_val, rank[i * n + j])
                else:
                    num = 1
                    now_set = set()
                    for ux, uy in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]:
                        if 0 <= ux < n and 0 <= uy < n and grid[ux][uy]:
                            rx = find(ux * n + uy)
                            if rx not in now_set:
                                now_set.add(rx)
                                num += rank[rx]
                    max_val = max(max_val, num)

        return max_val